package com.wh.accesscontrol.util;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class RoleCheckAspect {
    /**
     * Spring中使用@Pointcut注解来定义方法切入点
     * @Pointcut 用来定义切点，针对方法  @Aspect 用来定义切面，针对类
     * 后面的增强均是围绕此切入点来完成的
     * 此处仅配置被我们刚才定义的注解：AuthToken修饰的方法即可
     *
     */
    @Pointcut("@annotation(roleCheck)")
    public void doAuthToken(RoleCheck roleCheck) {
    }

    /**
     * 此处我使用环绕增强，在方法执行之前或者执行之后均会执行。
     */
    @Around("doAuthToken(roleCheck)")
    public Object deBefore(ProceedingJoinPoint pjp, RoleCheck roleCheck) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //获取访问该方法的权限信息
        String[] roles =roleCheck.roles();
        if (roles==null||roles.length==0){
            String id = request.getHeader("id");
            if (id!=null && !id.equals("")){
                return  pjp.proceed();
            }
            return "请登录后重试！";
        }else {
            String role = request.getHeader("role");
            for (String str:roles){
                if(str.equals(role)){
                    return pjp.proceed();
                }
            }
            return RetUtil.retError("没有权限访问！");
        }

    }

}
